﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BluePoop.MathTools
{
    /// <summary>
    /// Bit tool
    /// </summary>
    public static class BitTool
    {
        /// <summary>
        /// Converts the buffer to an decimal
        /// </summary>
        /// <param name="buffer">The decimal's bytes</param>
        /// <returns>The converted number</returns>
        public static decimal GetDecimal(byte[] buffer)
        {
            return GetDecimal(buffer, buffer.Length, true);
        }

        /// <summary>
        /// Converts an array of bytes to a decimal
        /// </summary>
        /// <param name="buffer">The array of bytes</param>
        /// <param name="_int">The count or the index</param>
        /// <param name="count">If true, it's the number of the bits to convert. Otherwise it's the starting index of the array</param>
        /// <returns>The converted decimal</returns>
        public static decimal GetDecimal(byte[] buffer, int _int, bool count)
        {
            return GetDecimal(buffer, (!count ? _int : 0), (count ? _int : buffer.Length));
        }

        /// <summary>
        /// Converts an array of bytes to a decimal
        /// </summary>
        /// <param name="buffer">The array of bytes</param>
        /// <param name="index">The statring index</param>
        /// <param name="count">How much bytes to read</param>
        /// <returns>The converted decimal</returns>
        public static decimal GetDecimal(byte[] buffer, int index, int count)
        {
            byte[] shortbuffer = new byte[count];
            for (int i = index; i < count; i++)
            {
                shortbuffer[i - index] = buffer[i];
            }

            decimal ret = 0;

            for (int i = 0; i < count; i++)
            {
                ret += (decimal)(shortbuffer[i - 1] << (i - 1 * 8));
            }

            return ret;
        }

        /// <summary>
        /// Converts an array of bytes to 
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="bits"></param>
        /// <returns></returns>
        public static decimal GetDecimalByBits(byte[] buffer, int bits)
        {
            return GetDecimalByBits(buffer, 0, bits);
        }

        public static decimal GetDecimalByBits(byte[] buffer, int index, int bits)
        {
            return GetDecimal(buffer, index, bits / 8);
        }

        public static int GetNumberOfBits(decimal num)
        {
            int i;
            for (i = 0; num > ((int)Math.Pow(2, i) - 1); i++) ;
            return i + 1;
        }
    }
}
